# encoding: utf-8
# 项目名称： drf-simple
# @File  : auth.py
# @Author: SunHao
# @Desc :  用户token控制
# @Date  :   16:17 2025/03/15
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api import models


class QueryParamsAuthentication(BaseAuthentication):
    """
        从接口的URL参数上获取token，并校验
    """

    def authenticate(self, request):
        # 做用户认证
        # 1 读取请求传递的token
        # 2 校验合法性
        # 3 返回值
        #  3.1 返回元组（11，22） 认证成功 request.use  request.auth
        #  3.2 抛出异常  认证失败 => 返回错误信息
        #  3.3 返回None  多个认证类 [类1、类2、类3、类4] => 匿名用户
        token = request.query_params.get('token')  # 从get中获取传递的token
        if not token:
            return None
            # 开始对比用户token,如果匹配上了就返回用户姓名
        user_object = models.SysUser.objects.filter(token=token).first()
        if user_object:
            return user_object, token
        return None

    def authenticate_header(self, request):
        return 'Token'


class HeaderAuthentication(BaseAuthentication):
    """
        从接口的请求头中获取token，并校验
    """

    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return None
        user_object = models.SysUser.objects.filter(token=token).first()
        if user_object:
            return user_object, token
        return None

    def authenticate_header(self, request):
        return 'Token'


class NoAuthentication(BaseAuthentication):

    def authenticate(self, request):
        raise AuthenticationFailed({"code": 4004, "message": "认证失败"})

    def authenticate_header(self, request):
        return 'Token'


# 博客系统案例

class BlogAuthentication(BaseAuthentication):
    """
        从接口的URL参数上获取token，并校验
    """

    def authenticate(self, request):
        token = request.query_params.get('token')
        if not token:
            return None
        user_object = models.UserInfo.objects.filter(token=token).first()
        if not user_object:
            return None
        return user_object, token

    def authenticate_header(self, request):
        return 'Token'
